package org.example.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.example.mapper.OperateLogMapper;
import org.example.pojo.OperateLog;
import org.example.utils.CurrentHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class OperateLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(org.example.anno.Log)")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        // 记录开始时间
        long start = System.currentTimeMillis();

        // 获取方法参数
        String methodParams = Arrays.toString(joinPoint.getArgs());

        // 执行目标方法
        Object proceed = joinPoint.proceed();

        // 计算耗时
        long elapsedTime = System.currentTimeMillis() - start;

        // 准备日志对象
        OperateLog olog = new OperateLog();
        olog.setOperateEmpId(getCurrentEmployeeId()); // 假设有一个方法可以获取当前操作人ID
        olog.setOperateTime(LocalDateTime.now());
        olog.setClassName(joinPoint.getTarget().getClass().getName());
        olog.setMethodName(joinPoint.getSignature().getName());
        olog.setMethodParams(methodParams);
        olog.setReturnValue(proceed != null ? proceed.toString() : "void");
        olog.setCostTime(elapsedTime);

        // 插入日志
        operateLogMapper.insert(olog);
        log.info("日志记录成功:{}", olog);

        return proceed;
    }

    // 假设的方法：根据实际情况修改以返回当前登录用户ID
    private Integer getCurrentEmployeeId() {
        return CurrentHolder.getCurrentId();
    }
}